package com.tjf.traffic;

import android.app.AppOpsManager;
import android.app.usage.NetworkStatsManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.tjf.traffic.adapter.TrafficDateAdapter;
import com.tjf.traffic.bean.TrafficDayInfo;
import com.tjf.traffic.utils.DateUtil;
import com.tjf.traffic.utils.NetworkStatsHelper;
import com.tjf.traffic.bean.TrafficBean;
import com.tjf.traffic.utils.TrafficFormat;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 流量监控首页 进行整个流量及每一天的总流量展示
 */
public class TrafficActivity extends AppCompatActivity {

    @BindView(R.id.traffic_list_rev)
    RecyclerView trafficListRev;


    @BindView(R.id.traffic_month_all_tv)
    TextView trafficMonthAllTv;
    @BindView(R.id.traffic_day_all_tv)
    TextView trafficDayAllTv;
    @BindView(R.id.traffic_month_downall_tv)
    TextView trafficMonthDownallTv;
    @BindView(R.id.traffic_month_upall_tv)
    TextView trafficMonthUpallTv;
    @BindView(R.id.traffic_day_downall_tv)
    TextView trafficDayDownallTv;
    @BindView(R.id.traffic_day_upall_tv)
    TextView trafficDayUpallTv;


    @BindView(R.id.total_traffic_tv)
    TextView totalTrafficTv;
    @BindView(R.id.total_up_traffic_tv)
    TextView totalUpTrafficTv;
    @BindView(R.id.total_down_traffic_tv)
    TextView totalDownTrafficTv;
    @BindView(R.id.traffic_app_sort_lly)
    LinearLayout trafficAppSortLly;
    @BindView(R.id.traffic_goback)
    ImageView trafficGoback;


    TrafficDateAdapter trafficDateAdapter;//每天流量展示适配器
    NetworkStatsManager networkStatsManager = null;//网络数据管理
    NetworkStatsHelper helper = null;//网络数据助手
    List<TrafficDayInfo> dateTraficlist = new ArrayList<>();//每天的流量集合

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_traffic);
        ButterKnife.bind(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            networkStatsManager = (NetworkStatsManager) getSystemService(NETWORK_STATS_SERVICE);
        }
        helper = new NetworkStatsHelper(networkStatsManager);

        trafficAppSortLly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkUserAppListPerMission();
            }
        });
        trafficGoback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onResume() {
        super.onResume();
        if (!hasPermissionToReadNetworkStats()) {
            Log.i("流量-", "==有权查看使用情况的应用的权限未授权==");
            return;
        }
        Log.i("流量-", "==有权查看使用情况的应用的权限授权成功==");
        setTrafficList();
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    public void setTrafficList() {

        TrafficBean monthTraffic = helper.getAllDay_MonthMobileInfo(this, false);
        TrafficBean dayTraffic = helper.getAllDay_MonthMobileInfo(this, true);
        trafficMonthAllTv.setText(String.format("当月已用总流量\n%s", TrafficFormat.formatByte(
                monthTraffic.getTotalData())));
        trafficDayAllTv.setText(String.format("当天已用总流量\n%s", TrafficFormat.formatByte(
                dayTraffic.getTotalData())));


        trafficMonthDownallTv.setText(String.format("当月下载流量\n%s", TrafficFormat.formatByte(
                monthTraffic.getRxBytes())));
        trafficMonthUpallTv.setText(String.format("当月上传流量\n%s", TrafficFormat.formatByte(
                monthTraffic.getTxBytes())));


        trafficDayDownallTv.setText(String.format("当天下载流量\n%s", TrafficFormat.formatByte(
                dayTraffic.getRxBytes())));
        trafficDayUpallTv.setText(String.format("当天上传流量\n%s", TrafficFormat.formatByte(
                dayTraffic.getTxBytes())));

        getDateAndMonthInfo();
        trafficDateAdapter = new TrafficDateAdapter(this,
                dateTraficlist, R.layout.traffic_date_item);
        trafficListRev.setLayoutManager(new LinearLayoutManager(this));
        trafficListRev.setAdapter(trafficDateAdapter);

    }


    public void startAppListPage() {
        Toast.makeText(this, "点击了应用排行", Toast.LENGTH_SHORT).show();
        startActivity(new Intent(TrafficActivity.this,
                TrafficAppActivity.class));

    }

    // 打开 "有权查看使用情况的应用"页面
    private void requestReadNetworkStats() {
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // 经过测试，只有在 Android 10 及以上加包名才有效果
            // 如果在 Android 10 以下加包名会导致无法跳转
            intent.setData(Uri.parse("package:" + getPackageName()));
        }
        startActivity(intent);
    }

    /**
     * 检查是否有有权查看使用情况的应用的权限
     *
     * @return true false
     */
    private boolean hasPermissionToReadNetworkStats() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            Log.i("流量-", "==当前版本小于23==");
            return true;
        }
        final AppOpsManager appOps = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, Process.myUid(), getPackageName());
        if (mode == AppOpsManager.MODE_ALLOWED) {
            return true;
        }
        requestReadNetworkStats();
        return false;

    }

    /**
     * 查询应用列表权限进行跳页
     */
    public void checkUserAppListPerMission() {
        startAppListPage();
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    public void getDateAndMonthInfo() {
        dateTraficlist.clear();

        long totalTx = 0;
        long totalRx = 0;
        long totalTraffic;

        List<Long> dateList = DateUtil.getListDayOfMonth();
        for (Long datelong : dateList) {
            TrafficBean oneTraffic = helper.getOneDayMobileInfo(this, datelong);

            TrafficDayInfo usageDate = new TrafficDayInfo();
            usageDate.setDateDay(datelong);
            usageDate.setDateDayStr(DateUtil.getDay(datelong));


            usageDate.setTotalRxBytes(TrafficFormat.formatByte(oneTraffic.getRxBytes()));
            usageDate.setTotalTxBytes(TrafficFormat.formatByte(oneTraffic.getTxBytes()));
            usageDate.setTotalTraffic(TrafficFormat.formatByte(oneTraffic.getTotalData()));
            dateTraficlist.add(usageDate);
            totalTx += oneTraffic.getTxBytes();
            totalRx += oneTraffic.getRxBytes();
        }
        totalTraffic = totalRx + totalTx;

        setTotalTraffic(TrafficFormat.formatByte(totalTraffic),
                TrafficFormat.formatByte(totalTx), TrafficFormat.formatByte(totalRx));
        Log.i("流量-", "==流量的汇总==\n"
                + TrafficFormat.formatByte(totalTraffic)
                + "\n上传流量合计：" +
                TrafficFormat.formatByte(totalTx)
                + "\n下载流量合计：" + TrafficFormat.formatByte(totalRx));
    }

    /**
     * 流量合计
     */
    public void setTotalTraffic(String totalTraffic, String upTraffic, String downTraffic) {
        totalTrafficTv.setText(String.format("总流量：%s", totalTraffic));
        totalUpTrafficTv.setText(String.format("上传总流量：%s", upTraffic));
        totalDownTrafficTv.setText(String.format("下载总流量：%s", downTraffic));
    }
}